﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Microsoft.Practices.Prism.Events;
using Reactor.Environment;
using Reactor.MiniManager.ViewModels;
using Reactor.MiniManager.Views;

namespace Reactor.MiniManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly IEventAggregator _eventAggregator;

        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            Icon = new BitmapImage(new Uri(@"pack://application:,,,/Images/Atom-Transparent-30x30.png"));
            _eventAggregator = Context.ServiceLocator.GetInstance<IEventAggregator>();
            DetailsWindows = new List<CoreDetailsWindow>();

            try
            {
                DataContext = new MainViewModel();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.GetBaseException().Message);
            }
        }

        public List<CoreDetailsWindow> DetailsWindows { get; private set; }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DetailsWindows.Clear();

            var vm = (MainViewModel) DataContext;
            vm.Dispose();

            Context.ServiceBus.Stop();
        }

        private void ListBoxItem_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            // Create viewmodel
            var selectedVm = (ReactorCoreViewModel) CoresList.SelectedItem;
            var vm = new CoreDetailsHostViewModel(_eventAggregator, selectedVm.Entity);

            // Create window, bind, and show
            var window = new CoreDetailsWindow { DataContext = vm };
            window.Closed += ChildWindow_Closed;
            window.ShowDialog();

            DetailsWindows.Add(window);
        }

        internal void ChildWindow_Closed(object sender, EventArgs e)
        {
            var window = (CoreDetailsWindow) sender;
            DetailsWindows.Remove(window);
        }
    }
}
